package org.cable.account.component;

import lombok.extern.slf4j.Slf4j;
import org.cable.account.config.SmsConfig;
import org.cable.common.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author hsj
 * @date 2023/10/25 16:01
 */
@Component
@Slf4j
public class SmsComponent {

    /**发送地址*/
    public static final String urlTemplate ="https://jmsms.market.alicloudapi.com/sms/send?mobile=%s&templateId=%s&value=%s";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SmsConfig smsConfig;


    /**
     * 发送短信验证码
     * @param target
     * @param templateId
     * @param value
     */
    public void send(String target,String templateId,String value){

        long begin = CommonUtil.getCurrentTimestamp();
        String url = String.format(urlTemplate, target, templateId, value);

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "APPCODE " + smsConfig.getAppCode());
        HttpEntity entity =  new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

        long end = CommonUtil.getCurrentTimestamp();
        log.info("url={},body={},耗时={}ms",url,response.getBody(),end-begin);
        if (response.getStatusCode().is2xxSuccessful()){
             log.info("发送短信验证码成功");
        }else {
            log.error("发送短信验证码失败:{}",response.getBody());
        }

    }

}
